const Controller = require('egg').Controller;
const formidable = require("formidable");
const awaitWriteStream = require('await-stream-ready').write;
const sendToWormhole = require('stream-wormhole');
const { v4: createuuid } =require('uuid')
const fs = require('fs');
const path = require('path');
const await = require('await-stream-ready/lib/await');

function parse(req) {//使用formidable解析formdata
  const form = new formidable.IncomingForm();
  return new Promise((resolve, reject) => {
      form.parse(req, (err, fields, files) => {
          resolve({ fields, files });
          reject((res) => { console.log(res) })
      });
  });
}

class ArticleController extends Controller {
 //查找作者文章
 async findUserArticle(){
  const {ctx}=this
  const {username}=ctx.request.body
  console.log(username,111111)
  const article=await ctx.service.article.findUserArticle(username)
  ctx.body=article
 }
 //获取文章封面
  async getArticlePicture(){
    const {ctx}=this
    const {uuid}=ctx.query
    const filePath=await this.service.article.downloadPicture(uuid)
    const fileStream = fs.createReadStream(filePath);
    // 设置响应的 Content-Type
    ctx.response.type = 'image/png'; // 根据实际文件类型设置
     // 将文件流作为响应的主体
    ctx.body = fileStream;
  }  
  //新增文章
  async addArticle() {
    const { ctx,app } = this;
   try{
  const extraParams = await parse(this.ctx.req);
  console.log("FormData中的普通参数-----------", extraParams.fields);
  console.log("FormData中的文件--------------", extraParams.files);
  const file = extraParams.files.file[0];  //得到文件upfile，我的vue传过来的file就叫做upfile，所以这里取出来也是通upfile
  const stream = fs.createReadStream(file._writeStream.path);//创建文件读取流，从临时文件中读取
  const uuid=createuuid()
  const fileName = `${uuid}.png`;//文件命名
      const {title,content,channel}=extraParams.fields
     const newtitle= title.join('')
     const newcontent= content.join('')
     const newchannel= channel.join('')
     const target = path.join(app.baseDir,'app/public/articlepic', fileName);//目标路径
     const writeStream = fs.createWriteStream(target);//将文件写入目标路径
     try {
      await awaitWriteStream(stream.pipe(writeStream));//等待完成写入
  } catch (err) {
      await sendToWormhole(stream);//关闭临时文件
      console.log(err)
  }
      let result = await ctx.service.article.addArticle({
        uuid,
        title:newtitle,
        content:newcontent,
        channel:newchannel,
        picstorage:target
       })
    ctx.body=result
   } catch(error){
    console.log(error)
    ctx.body='fail'
   }
  }
//修改文章
async updateArticle() {
  const { ctx,app } = this;
 try{
const extraParams = await parse(this.ctx.req);
const {title,content,channel,uuid}=extraParams.fields
console.log("FormData中的普通参数-----------", extraParams.fields);
console.log("FormData中的文件--------------", extraParams.files);
console.log(extraParams.files)
if(Object.keys(extraParams.files).length!=0){
  await ctx.service.article.deleteArticlePicture(uuid)
  const fileName = `${uuid}.png`;//文件命名
  const file = extraParams.files.file[0];  //得到文件upfile，传过来的file叫做files，所以这里取出来也是通files
  const stream = fs.createReadStream(file._writeStream.path);//创建文件读取流，从临时文件中读取
  const target = path.join(app.baseDir,'app/public/articlepic', fileName);//目标路径
  const writeStream = fs.createWriteStream(target);//将文件写入目标路径
  try {
   await awaitWriteStream(stream.pipe(writeStream));//等待完成写入
} catch (err) {
   await sendToWormhole(stream);//关闭临时文件
   console.log(err)
}
}
// const uuid=createuuid()
// const fileName = `${uuid}.png`;//文件命名
    
   const newtitle= title.join('')
   const newcontent= content.join('')
   const newchannel= channel.join('')
   let result = await ctx.service.article.updateArticle({
      uuid:uuid,
      title:newtitle,
      content:newcontent,
      channel:newchannel,
     })
  ctx.body=result
 } catch(error){
  console.log(error)
  ctx.body='fail'
 }
}
}

module.exports = ArticleController;
